package org.james.deleter.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.lang3.StringUtils;

public class FileUtils extends org.apache.commons.io.FileUtils {
	
	public static boolean checkFileExtension(String fileName,String type){
		if(StringUtils.isNotBlank(fileName) &&
		   StringUtils.isNotBlank(type) &&
		   StringUtils.indexOf(fileName, ".") >= 0){
			String extension = StringUtils.substring(fileName, 
					StringUtils.lastIndexOf(fileName, ".")+1, fileName.length());
			if(StringUtils.equalsIgnoreCase("excel", type)){
				if(StringUtils.equalsIgnoreCase(extension, "xls") ||
				   StringUtils.equalsIgnoreCase(extension, "xlsx")){
					return true;
				}
			}else if(StringUtils.equalsIgnoreCase("excel-2003", type)){
				if(StringUtils.equalsIgnoreCase(extension, "xls")){
					return true;
				}
			}else if(StringUtils.equalsIgnoreCase("img", type)){
				if(StringUtils.equalsIgnoreCase(extension, "jpg") ||
				   StringUtils.equalsIgnoreCase(extension, "bmp") ||
				   StringUtils.equalsIgnoreCase(extension, "png") ||
				   StringUtils.equalsIgnoreCase(extension, "jpeg") ||
				   StringUtils.equalsIgnoreCase(extension, "gif")){
					return true;
				}
			}		
		}
		return false;
	}
	
	public static String getFileExtension(String fileName){
		String[] arr = StringUtils.split(fileName, ".");
		if(arr.length > 1){
			return arr[arr.length-1];
		}
		return null;
	}
	
	public static String getNameWithoutExtension(String fileName){
		String[] arr = StringUtils.split(fileName, ".");
		if(arr.length > 0){
			return arr[0];
		}
		return null;
	}
	
	public static synchronized void writeToFile(InputStream inputStream, File file) 
			throws IOException {
		if(file.exists()){
			file.delete();
		}
    	file.createNewFile();
        int read = 0;
        byte[] bytes = new byte[1024];
        OutputStream out = new FileOutputStream(file);
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    }
	
	public static void main(String[] args) throws IOException {
		cleanDirectory(new File("D:/userdata/its_user_data/app_file/2016-08-11/android"));
	}
}
